package com.yu.common.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author jiangting
 * description:
 * date: 2023/3/10
 */
@MappedTypes({Object.class})
public class JsonbTypeHandler extends BaseTypeHandler<Object> {
    //报错的话，请将pom文件的引入graphql的地方<version></version>标签注释掉
    private static final PGobject jsonObject = new PGobject();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
        throws SQLException {
        if (ps != null) {
            JsonbTypeHandler.jsonObject.setType("jsonb");
            JsonbTypeHandler.jsonObject.setValue(JSON.toJSONString(parameter, SerializerFeature.WriteMapNullValue));
            ps.setObject(i, JsonbTypeHandler.jsonObject);
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        Object object = JSON.parse(str);
        if (object instanceof JSONArray) {
            JSONArray parseObject = JSONObject.parseObject(str, JSONArray.class);
            return parseObject;
        }
        return object;

    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.getObject(columnIndex);
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.getObject(columnIndex);
    }
}
